package com.lanou3g.code0514;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/14;
 * Otherwise, I don't know who created it either
 */

@WebServlet(name = "SearchServlet" ,urlPatterns = "/search")
public class SearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        // 获取前端传过来的参数
        String key = request.getParameter("key");

        // 加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");

            Properties properties = new Properties();
            // 使用 类名.class.getClassLoader()
            // 获取 类加载器
            // 类加载器的getResourceAsStream
            // 是相对于 src路径下的
            InputStream is = SearchServlet.class.getClassLoader()
                    .getResourceAsStream("jdbc.properties");
            properties.load(is);

            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/lanou_news",
                    properties);

            String sql = "SELECT * FROM my_news WHERE title like ?";

            PreparedStatement statement = conn.prepareStatement(sql);

            statement.setString(1,"%" + key + "%");

            ResultSet rs = statement.executeQuery();

            PrintWriter pw = response.getWriter();

            while (rs.next()){
                int id = rs.getInt("id");
                String title = rs.getString("title");
                pw.println(id + "-" + title);
                pw.println("<br/>");
            }

            rs.close();
            statement.close();
            conn.close();
            is.close();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
